<template>
  <div class="map-container">

    <div id="map" ref="container" class="amap"/>

    <div class="input-card" v-permission="['edit:map:block']">
      <el-button size="small" @click="createPolygon()">新建区块</el-button>
      <el-button size="small" @click="edit()">开始编辑区块</el-button>
      <el-button size="small" @click="close()">结束编辑区块</el-button>
      <el-button size="small" @click="remove()">删除区块</el-button>
      <el-button size="small" @click="editInfo()">保存区块信息</el-button>

    </div>


    <el-dialog
      title="区块信息"
      class="dialog"
      :visible.sync="dialogVisible"
      width="600px"
    >
      <el-form
        ref="blockForm"
        :model="blockForm"
        :rules="rules"
        size="small"
        label-width="80px"
      >
        <el-form-item prop="area" label="区域面积">
          <el-input v-model.number="blockForm.area"/>
        </el-form-item>
        <el-form-item prop="level" label="区块等级">
          <el-select v-model="blockForm.level">
            <el-option label="1" value="1"/>
            <el-option label="2" value="2"/>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button
            :loading="loading"
            type="primary"
            @click="submitForm(true)"
          >
            保存区块信息
          </el-button>

          <el-button
            @click="cancelForm"
          >
            返回
          </el-button>
        </el-form-item>
      </el-form>

    </el-dialog>

  </div>

</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader';
import { amapKey } from '@/settings'
import { getAll } from "@/api/business/demand";
import crudBlock, { getLocList } from "@/api/map";

export default {
  name: "AMap",

  data() {
    return {
      map: null,
      keyword: '',
      lng: '',
      lat: '',
      marker: null,
      address: '',
      polyEditor: null,
      mouseTool: null,
      dialogVisible: false,
      loading: false,
      blockForm: {
        area: 0,
        level: 1,
        id: 0,
        name: '',

      },
      rules: {},
      isEdit: false,
      blockId: null,
      polygonList: [],
    }
  },
  beforeCreate() {
    AMapLoader.load({
      "key": amapKey, // 申请好的Web端开发者Key，首次调用 load 时必填
      "version": "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      "plugins": ['AMap.MouseTool', 'AMap.PolygonEditor'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      "AMapUI": { // 是否加载 AMapUI，缺省不加载
        version: '1.1',
        "plugins": []// 需要加载的 AMapUI ui插件
      },

    }).then(AMap => {
      this.initMap(AMap);
      this.setPolygon(AMap);

    }).catch(e => {
      console.error(e);
    })
  },
  methods: {
    initMap(AMap) {
      // this.map = new AMap.Map("container");
      // 或者使用 $refs 获取节点
      const self = this;
      const $map = this.$refs.container;

      self.map = new AMap.Map(
        $map, {
          center: [121.03641288313125, 31.52016354425492],
          zoom: 15
        });

      self.polyEditor = new AMap.PolygonEditor(self.map);
      // self.mouseTool = new AMap.MouseTool(self.map)
      // self.mouseTool.on('draw', function(event) {
      //   // event.obj 为绘制出来的覆盖物对象
      //   console.log('event.obj', event.obj._opts.path);
      //   self.mouseTool.close(false);
      // })

      // 获取关键点信息
      getLocList().then(res => {
        let locList = res.data;
        for (let i = 0; i < locList.length; i++) {
          let item = locList[i];
          let lng = item.lon;
          let lat = item.lat;
          let name = item.name;
          let text = new AMap.Text({
            text: name,
            anchor: 'center', // 设置文本标记锚点
            style: {
              'padding': '.75rem 1.25rem',
              'margin-bottom': '1rem',
              'border-radius': '.25rem',
              'background-color': 'white',
              'width': '15rem',
              'border-width': 0,
              'box-shadow': '0 2px 6px 0 rgba(114, 124, 245, .5)',
              'text-align': 'center',
              'font-size': '20px',
              'color': 'blue'
            },
            position: [lng, lat]
          });
          // text.setMap(self.map);

          let markerContent = `<div class="map-important"></div>`;

          console.log(res)
          var marker = new AMap.Marker({
            position: new AMap.LngLat(lng, lat),   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
            title: name,
            // label: { content: name, direction: 'center' },
            content: markerContent,
          });
          self.map.add(marker);
        }
      }).catch(err => {
        console.log(err)
      })

      getAll().then(function(response) {

        let hList = response.data;
        for (let i = 0; i < hList.length; i++) {
          let item = hList[i];
          let lng = item.lon;
          let lat = item.lat;
          let num = item.houseLesseeList.length
          let icon = 'map-marker'
          let markerContent = '' ;
          switch (item.grid) {
            case '庆丰':
              markerContent = '' +
                '<div class="map-marker map-marker2"></div>';
              break;
            case '凤中':
              markerContent = '' +
                '<div class="map-marker map-marker3"></div>';
              break;
            case '黄桥':
              markerContent = '' +
                '<div class="map-marker map-marker4"></div>';
              break;
            case '园区':
              markerContent = '' +
                '<div class="map-marker map-marker5"></div>';
              break;
            case '维新':
              markerContent = '' +
                '<div class="map-marker map-marker6"></div>';
              break;
            case '泥泾':
              markerContent = '' +
                '<div class="map-marker map-marker7"></div>';
              break;
            default:
              markerContent = '' +
                '<div class="map-marker"></div>';
              break;
          }
          var marker = new AMap.Marker({
            position: new AMap.LngLat(lng, lat),   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
            content: markerContent,
          });
          marker.setExtData(item)

          marker.on('click', function(e) {
            self.sendCompany(e.target.getExtData());
          })

          self.map.add(marker);
        }
      }).catch(err => {
        console.log(err)
      })
    },
    sendCompany(list) {
      this.$emit('click', list)
    },
    setPolygon() {
      const self = this;
      this.map.remove(self.polygonList);
      self.polygonList = [];

      crudBlock.getRegionList().then(function(response) {
        let regionList = response.data;
        for (let i = 0; i < regionList.length; i++) {
          let item = regionList[i];
          let path = JSON.parse(item.geometry);
          let type = item.level;
          let color = '#1791fc'
          if (type === "2") {
            color = '#17fcac'
          }
          if (path) {
            let polygon = new AMap.Polygon({
              path: path,
              strokeColor: "green",
              strokeWeight: 6,
              strokeOpacity: 0.2,
              fillOpacity: 0.4,
              fillColor: color,
              zIndex: 50,
              bubble: true,
            });
            self.polygonList.push(polygon)
            polygon.setExtData({
              id: item.id,

            });

            self.map.add(polygon);

            polygon.on('click', function(e) {
              console.log(polygon)
              self.polyEditor.setTarget(polygon);

            })
          }
        }
      }).catch(function(err) {
        console.log(err)
      })

      // 折线的节点坐标数组，每个元素为 AMap.LngLat 对象
      // var path =
      //   [
      //     [
      //       121.030103,
      //       31.504891
      //     ],
      //     [
      //       121.04,
      //       31.512031
      //     ],
      //     [
      //       121.044463,
      //       31.508388
      //     ],
      //     [
      //       121.040468,
      //       31.505647
      //     ],
      //     [
      //       121.042417,
      //       31.504899
      //     ],
      //     [
      //       121.043878,
      //       31.505813
      //     ],
      //     [
      //       121.048025,
      //       31.502061
      //     ],
      //     [
      //       121.03691,
      //       31.494889
      //     ]
      //   ]
      // ;

    },
    edit() {
      if (this.polyEditor.getTarget()) {

        // 缩放地图到合适的视野级别
        this.polyEditor.open();
      } else {
        this.$message.error('请先选择要编辑的区域')
      }

    },
    remove() {
      if (this.polyEditor.getTarget()) {
        this.polyEditor.close();
        // this.map.remove(this.polyEditor.getTarget())
        let id = this.polyEditor.getTarget().getExtData().id;
        if (id) {
          crudBlock.del(id).then(res => {
            this.$message.success('删除成功')
            this.setPolygon();

          }).catch(err => {
            this.$message.error('删除失败')
          })
        }
      } else {
        this.$message.error('请先选择要编辑的区域')
      }

    },
    close() {
      this.polyEditor.close();
      if (this.polyEditor.getTarget()) {
        let path = [];
        // 获取多边形坐标
        path = this.polyEditor.getTarget()._opts.path;
        console.log(path)
      }
    },
    draw() {
      this.mouseTool.polygon({
        strokeColor: "#FF33FF",
        strokeWeight: 6,
        strokeOpacity: 0.2,
        fillColor: '#1791fc',
        fillOpacity: 0.4,
        // 线样式还支持 'dashed'
        strokeStyle: "solid",
        // strokeStyle是dashed时有效
        // strokeDasharray: [30,10],
      })
    },
    createPolygon() {
      this.polyEditor.close();
      this.polyEditor.setTarget();
      this.polyEditor.open();
      // let polygon=this.polyEditor.getTarget();
      // if(polygon){
      //   let path = polygon._opts.path;
      //   console.log(path)
      // }
      let self = this;
      this.polyEditor.on('add', function(data) {

        var polygon = data.target;
        self.polygonList.push(polygon)
        polygon.on('click', () => {
          self.polyEditor.setTarget(polygon);
        })
      })
    },
    editInfo() {
      this.polyEditor.close();
      let polygon = this.polyEditor.getTarget();
      let id = polygon.getExtData().id;
      if (polygon) {
        let polygonId = polygon.getExtData().id;
        let path = polygon._opts.path;
        this.blockForm.geometry = JSON.stringify(path);
        if (polygonId) {
          let self = this;
          crudBlock.get(id).then(function(res) {
            self.blockForm = Object.assign({}, self.blockForm, res.data);
            self.blockForm.geometry = JSON.stringify(path)
            self.dialogVisible = true;
            self.isEdit = true;
          }).catch(function(err) {
            console.log(err)
          })
        } else {
          this.isEdit = false;
          this.dialogVisible = true;
        }

      } else {
        this.$message.error('请先选择要保存的区域')
      }

    },
    submitForm() {
      this.$refs.blockForm.validate(valid => {
        if (!valid) {
          return
        }
        this.loading = true;
        if (this.isEdit) {
          crudBlock.edit(this.blockForm).then(() => {
            this.$notify({
              title: '成功',
              message: '修改区块信息成功',
              type: 'success',
              duration: 2000
            })
            this.loading = false
            this.cancelForm();
            this.setPolygon();
          })
        } else {
          crudBlock.add(this.blockForm).then(() => {
            this.$notify({
              title: '成功',
              message: '新增区块信息成功',
              type: 'success',
              duration: 2000
            })
            this.loading = false
            this.cancelForm();
            this.setPolygon();

          })
        }
      })
    },
    cancelForm() {
      this.dialogVisible = false;
    }
  },

}

</script>

<style scoped>
.map-container {
  width: 100%;
  height: calc(100vh - 90px);
  position: relative;
}

.tipWrapper {
  position: absolute;
  top: 100px;
  right: 10px;
}

.amap {
  width: 100%;
  height: 100%;

}

.input-card {
  position: absolute;
  top: 10px;
  left: 10px;
  background: white;
  padding: 10px;
}

</style>
